<template>
    <div class="container">
        <m-header :closeFn="() => this.$router.push('/index')">购买校车车票</m-header>
        <div class="main">
            <div class="school-wrap">
                <span>当前学校：</span>
                <span class="bold">{{schoolName}}</span>
                <!--有特权码不修改-->
                <!--240130 yan 地址栏传入学校不显示修改按钮-->
                <div v-if="!value.privileged_code && !$route.query.ticket_typall_id" class="btn" @click="onShow('school')">修改</div>
            </div>
            <ul class="box tab-wrap" ref="tabWrap">
                <li v-for="(item,index) in tabList" @click="tabChange(index)" :class="{'active':active === index}">{{item.packag_type_name}}</li>
                <i v-if="tabList.length" class="line" :style="{transform: `translateX(${tabLinePosition}px) translateX(-50%)`}"></i>
            </ul>
            <div class="box station-wrap">
                <div class="cell" @click="onShow('onStation')" v-if="curTabId !== 'tplx002'">
                    <m-form :field="fields.onStationField" :value="value.stop_name_go">
                        <template slot="label">
                            <div class="cell-left gdot" slot="label">去程上车点</div>
                        </template>
                    </m-form>
                </div>
                <div class="cell" @click="onShow('offStation')" v-if="curTabId !== 'tplx001'">
                    <m-form :field="fields.offStationField" :value="value.stop_name_leave">
                        <template slot="label">
                            <div class="cell-left rdot" slot="label">回程下车点</div>
                        </template>
                    </m-form>
                </div>
            </div>
            <div class="box schedule-wrap">
                <div class="cell" @click="onShow('schedule')">
                    <m-form :field="fields.scheduleField" :value="value.shuttle_name"></m-form>
                </div>
                <div class="info" v-show="value.shuttle_id">
                    <div class="h2" v-if="curTabId !== 'tplx002'">去程：{{value.go_departure_time}}发车，{{value.go_arrive_time}}到校</div>
                    <div class="h2" v-if="curTabId !== 'tplx001'">回程：{{value.leave_departure_time}}发车，{{value.leave_arrive_time}}到站</div>
                    <div class="h2 margin-bot10">时段：{{value.service_period}}，座位号以照管员安排</div>
                    <div class="h2 margin-bot10">说明：{{value.mark}}</div>
                    <div class="h2 margin-bot10 bold">{{value.sell_dateime_start}}开售</div>
                </div>
                <div class="ticket-type" v-show="value.shuttle_id">
                    <div class="h1 title">请选择票据类型</div>
                    <van-radio-group v-model="ticket_typall_id">

                        <van-radio :name="item.ticket_typall_id" v-for="item in packageList">
                            <template #icon="props">
                                <div class="icon-radio" :class="{active: props.checked}"></div>
                            </template>
                            <div class="h1">{{item.ticket_typall_name}}({{item.Order_amount}}元)</div>
                            <div class="h3 margin-bot10">有效期：{{item.effective_time_start}}至{{item.effective_time_end}}</div>
                        </van-radio>
                    </van-radio-group>
                </div>
            </div>
            <div class="box passenger-wrap">
                <div class="cell" @click="onShow('passenger')">
                    <m-form :field="fields.passengerField" :value="value.passengers_name"></m-form>
                </div>
                <div class="cell" v-show="value.passengers_id">
                    <m-form :field="fields.gradeClassField" :value="value.class_" @change="onChange"></m-form>
                </div>
                <div class="cell" v-show="value.passengers_id && value.stop_id_leave">
                    <m-form :field="fields.backHomeField" :value="value.leave_school_name" @change="onChange"></m-form>
                    <div class="tips" v-show="value.leave_school_name === '家长接送'">
                        <van-icon name="warning-o" />
                        用户未能及时在站点接学生，我公司会将小孩送回原学校并及时通知用户。由用户自行接回学生，并承担学生下车后的安全责任及费用。
                    </div>
                </div>
            </div>


            <div class="footer">
                <van-button class="btn" color="#24C373" @click="onPay" v-prevent-re-click>微信支付</van-button>
            </div>
        </div>

        <van-popup v-model="showPopup" position="right">
            <choose-school @close="onClose" @select="onSelect" v-if="chooseType === 'school'" />
            <choose-station type="on" @close="onClose" @select="onSelect" v-if="chooseType === 'onStation'" />
            <div><choose-station :tp-id="curTabId" :go-id="value.stop_id_go" type="off" @close="onClose" @select="onSelect" v-if="chooseType === 'offStation'" /></div>
            <choose-schedule :type="curTabId" :go-id="value.stop_id_go" :leave-id="value.stop_id_leave" @close="onClose" @select="onSelect" v-if="chooseType === 'schedule'" />
            <choose-passenger @close="onClose" @select="onSelect" v-if="chooseType === 'passenger'" :isComponent="true"/>
        </van-popup>
        <m-agreement v-model="showAgreement" :agreement_id="agreementId" @agree="onAgree"></m-agreement>

        <!--显示手写签名-->
        <!--<van-popup v-model="showSignPopup" position="right" @opened="bindShowESign">
            <div class="esign-wrap">
                <div class="esign" ref="esignWrap">
                    <vue-esign
                            v-if="showSign"
                            ref="esign"
                            :width="esignW"
                            :height="esignH"
                            :isCrop="isCrop"
                            :lineWidth="lineWidth"
                            :lineColor="lineColor"/>
                </div>
                <div class="btns">
                    <div class="btn-wrap"><van-button color="#24C373" @click="handleGenerate" class="btn">确定签名</van-button></div>
                    <div class="btn-wrap"><van-button color="#24C373" @click="handleReset" class="btn">清空画板</van-button></div>
                    <div class="btn-wrap"><van-button @click="cancelSign" class="btn">取消购票</van-button></div>
                    <img :src="imgSrc" alt="">

                </div>
               &lt;!&ndash; <div>
                    <div class="wrap">
                    </div>
                </div>&ndash;&gt;
            </div>
        </van-popup>-->
    </div>
</template>

<script>
  import form from '@/components/form/form'
  import chooseSchool from './components/chooseSchool'
  import chooseStation from './components/chooseStation'
  import chooseSchedule from './components/chooseSchedule'
  import passengerList from '@/pages/passengerList/passengerList'
  import agreement from '@/components/agreement/agreement'
  import { RadioGroup, Radio,Popup, Toast  } from 'vant';
  import { getSession,setSession } from '@/utils/store';
  import {getPackage,getShuttlePackage,lockTicket,unLockTicket,getLockResult,unifiedorder,getLeaveSchoolType,getShuttle,lockTicketTest,checkPriorityPassengers,uploadFile,updateOrderImg,checkAgreement} from "../../request/api";
  import {mapState,mapGetters,mapMutations,mapActions} from 'vuex';
  import {setToken} from "../../utils/cache";
  import {crtTimeFtt} from "../../utils/utils";
  import {preventReClick} from "../../utils/plugins";
  import vueEsign from 'vue-esign'
  import {imgCompress,addWatermark,file2Img,fillText, base64ImgtoFile} from "../../utils/img";
  import {getLocation} from "../../utils/wx";
  import {mapGeocoder} from "../../request/api";
  import dialog from '@/utils/dialog'

  export default {
    name: "buyTicket",
    components: {
      "m-form": form,
      "chooseSchool": chooseSchool,
      "chooseStation": chooseStation,
      "chooseSchedule": chooseSchedule,
      "choosePassenger": passengerList,
      "m-agreement": agreement,
      [RadioGroup.name]: RadioGroup,
      [Radio.name]: Radio,
      [Popup.name]: Popup,
      vueEsign
    },
    computed: {
      ...mapState({
        schoolId: state => state.school.schoolId,
        schoolName: state => state.school.schoolName,
        customerName: state => state.user.customerName,
        customerPhone: state => state.user.customerPhone,
      }),
      tabLinePosition(){
        let position = 0;
        if (!this.tabList.length)return;
        let width = (this.$refs.tabWrap.offsetWidth - 30)/this.tabList.length,    //左右行边距15，3个tab元素
          {active} = this;
        position = (active + 0.5) * width;
        return position
      },
      curTabId(){
        return this.tabList[this.active] && this.tabList[this.active].packag_type_id
      }
    },
    data(){
      return {
        // 录入字段参数
        fields: {
          onStationField:{
            type: 'picklist',
            disabled: true,
          },
          offStationField: {
            type: 'picklist',
            disabled: true,

          },
          scheduleField: {
            label: '班次',
            type: 'picklist',
            disabled: true,
          },
          passengerField: {
            label: '乘车人',
            type: 'picklist',
            disabled: true,
            field_id: 'passengers_id',
          },
          gradeClassField: {
            label: '年级班级',
            type: 'text',
            disabled: false,
            field_id: 'class_',
          },
          backHomeField: {
            label: '回程下车',
            type: 'picklist',
            options: [],
            field_id: 'leave_school_name',
            entityKey: 'leave_school_name',
          },
        },

        tabList: [],  //套票类型
        active: 0,  //套票类型单选
        radio: '1', //票据类型单选

        showPopup: false,   //现在选择页面
        chooseType: '', //选择类型

        showAgreement: false,   //显示弹窗

        packageList: [], //班车套票列表

        value: {},  //已选数据
        ticket_typall_id: '', //票种id

        isPriority: undefined,

        //显示手写签名
        showSignPopup: false,
        esignH: 0,
        esignW: 0,
        lineWidth: 2,
        lineColor: '#000000',
        resultImg: '',
        isCrop: false,
        showSign: false,

        agreementId: '001',
        imgSrc:'',
        signImg: '',
        agreementImg: '',

        showPopover: true,


      }
    },
    methods: {

      ...mapMutations({
        setSchool: 'SET_SCHOOL'    //this.setSchool(obj);
      }),
      tabChange(index){
        if (index == this.active) return
        this.active = index;
        //切换清空数据
        this.value.stop_id_go = '';
        this.value.stop_name_go = '';
        this.value.stop_id_leave = '';
        this.value.stop_name_leave = '';
        this.value.shuttle_id = '';
        this.value.shuttle_name = '';
      },
      async onPay(){
        await this.checkCustomerData();
        // await this.getLocation();

        let {value,active,curTabId} = this,
          arr = [
            {field_id: 'privileged_code'},
            {field_id: 'school_id',errmsg: '请选择学校'}
            ];
        if (curTabId !== 'tplx002') arr.push({field_id:'stop_id_go',errmsg: '请选择去程上车点'});
        if (curTabId !== 'tplx001') arr.push({field_id:'stop_id_leave',errmsg: '请选择回程下车点'});
        arr = [...arr,
          {field_id: 'shuttle_id',errmsg: '请选择班次'},
          {field_id: 'shuttle_seat_id'},
          {field_id: 'passengers_id',errmsg: '请选择乘车人'},
          {field_id: 'class_',errmsg: '请输入年级班级'},
        ];
        if (value.stop_id_leave){
          arr.push(
            {field_id:'leave_school_id',errmsg: '请选择回程下车方式'}
          )
        }
        let post = {
          // "shuttle_id": "string",
          "packag_type_id": curTabId,
          "ticket_typall_id": this.ticket_typall_id,

          // "ticket_typall_id": "string",
          // "passengers_id": "string",
          // "school_id": "string",
          // "stop_id_go": "string",
          // "stop_id_leave": "string",
          // "privileged_code": "string",
        },
          flag = false;
        for (let i = 0;i < arr.length; i++){
          let item = arr[i],
            id = item.field_id,
            val = value[id];
          if (!val && item.errmsg){
            flag = true;
            this.$Toast(item.errmsg)
            break
          }
          /*if (id === 'class_' && !/^[0-9]{3,4}$/.test(val)){
            this.$Toast('年级班级格式不正确')
            flag = true;
            break
          }*/
          post[id] = val;
        }
        if (flag)return;
        console.log('提交数据',post);
        this.post = post;

        this.$Loading();
        //检查是否需要签名
        this.checkSignature().then(res =>{
          //需要签名显示弹窗
          if (res) {
            this.$toast.clear();
            this.showAgreement = true;
          }
          else {
            //不需要签名直接锁票发起支付
            this.lockTicket().then(() =>{
              this.$toast.clear();
              this.weUnifiedorder(this.out_trade_no).then(() => {})
            })
          }
        })


      },
      //已阅读并同意协议签名
      async onAgree(val){
        this.$Loading();
        // if (val){
        //优先购票
        await this.isPriorityTicket();

        // console.log('锁票')
          // return;
        this.lockTicket().then(() =>{
          this.$toast.clear();
          //  231113 yan 接收协议照片，签名照片
          this.agreementImg = val.agreementImg;
          this.signImg = val.signImg;
          this.showAgreement = false;
          // this.showSignPopup = true;
          this.$Loading();
          //  上传协议和签名
          this.submitOrderImg().then(() => {
            this.$toast.clear();
            console.log('发起支付');
            //发起支付
            // let {out_trade_no} = this;
            this.weUnifiedorder(this.out_trade_no).then(() => {})
          });
        })
          /*lockTicket(this.post).then(res =>{
            let {shuttle_id} = this.post
            if (res.errmsg === '已锁位不能重复提交') {
                setTimeout(() => {
                  this.$router.push({path: '/ticketDetail',query: {shuttle: shuttle_id}})
                },2000);
                return
            }

            if (res.errmsg === '没有优先权'){
              let {priority_minute,sell_dateime_start,passengers_name,school_name,shuttle_id} = this.value;
              let endTime =  sell_dateime_start && new Date(crtTimeFtt(sell_dateime_start,'YYYY/MM/DD HH:mm:ss')).getTime(),
                lastTime = endTime + priority_minute *60 *1000,
                time = crtTimeFtt(lastTime,'YYYY年MM月DD日HH时mm分ss秒'),
                title = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_SYSTITLE : window.webConfig.webSystemTitle;
              this.$toast({
                duration: 2500,
                type: 'loading',
                onClose: () => {
                  this.$toast({
                    duration: 0,
                    message: `本次抢购失败，请稍后再试`,
                    className: 'm-van-loading',
                    closeOnClickOverlay: true,
                    overlay: true
                  })
                }
              })
             /!* this.$toast({
                duration: 0,
                message: `温馨提示：感谢新客户选择${title}，请您在${time}后购票。`,
                className: 'm-van-loading',
                closeOnClickOverlay: true,
                overlay: true
              })*!/
              return;
            }

            if (res.errcode !== 0)return;
            let data = res.row[0];

            this.$toast({
              duration: 0,
              message:'订单已提交，排队处理中...\n请勿退出当前页面！',
              forbidClick: true,
              type: 'loading',
              className: 'm-van-loading'
            })

            this.out_trade_no = data.out_trade_no;

            this.checkLockResult(data.out_trade_no, data.query_cycle_second || 1 ,shuttle_id).then(() => {
              this.$toast.clear();
            //  231113 yan 接收协议照片，签名照片
              this.agreementImg = val.agreementImg;
              this.signImg = val.signImg;
              this.showAgreement = false;
              // this.showSignPopup = true;

               this.$Loading();
                //  上传协议和签名
              this.submitOrderImg().then(() => {
                this.$toast.clear();
                console.log('发起支付');
                //发起支付
                // let {out_trade_no} = this;
                this.weUnifiedorder(data.out_trade_no).then(() => {})
              });

            //  发起支付
              /!*this.weUnifiedorder(data.out_trade_no).then(() => {})*!/
            })
          })*/
        // }
      },
      //显示弹窗
      onShow(type){
        //240127 yan 修改 取消根据特权码限制是否可操作，改为根据地址栏传入信息，传入已有信息的不可操作
        /*/!*有特权码不修改*!/
        if (['school','offStation','onStation','schedule'].includes(type) && this.value.privileged_code) {
          return
        }*/
        let {query} = this.$route,
          {privileged_code,school_id,school_name,packag_type_id,shuttle_id,stop_id_go,stop_name_go,stop_id_leave,stop_name_leave } = query;
        if (type === 'school' && school_id) return;     //学校
        if (type === 'onStation' && stop_id_go && this.value.privileged_code) return; // 上车点   240130 有特权码才限制上车点
        if (type === 'offStation' && stop_id_leave && this.value.privileged_code) return; //下车点 240130 有特权码才限制下车点
        if (type === 'schedule' && shuttle_id) return; //班车
        //240127 end

        this.chooseType = type;
        if (['offStation','onStation'].includes(type) && !this.value.school_id ){
          Toast('请先选择学校');
          return;
        }
        if (type === 'offStation' && this.curTabId === 'tplx003' && !this.value.stop_id_go) {
          Toast('请先选择去程上车站点');
          return;
        }
        if (type === 'schedule') {
          if (this.curTabId !== 'tplx002' && !this.value.stop_id_go) {
            Toast('请先选择去程上车站点');
            return;
          }
          if (this.curTabId !== 'tplx001' && !this.value.stop_id_leave) {
            Toast('请先选择回程上车站点');
            return;
          }
        }

        this.showPopup = true;
      },
      //关闭弹窗
      onClose(){
        this.showPopup = false;
      },
      //弹窗选择
      onSelect(data){
        this.onClose();
        let {chooseType} = this;
        if (chooseType.indexOf('Station') > 0){
          this.value= {...this.value,...data};
        }
        if (chooseType === 'schedule') {
          console.log(data);
          this.value = {...this.value,...data,}
          this.getShuttlePackage_();
        }
        if (chooseType === 'passenger'){
          //增加默认值回程下车方式
          let leave_school_id_def = 'js001',
            leave_school_name_def = '自行回家',
            leave_school_id = data.leave_school_id || this.value.leave_school_id || leave_school_id_def,
            leave_school_name = data.leave_school_name || this.value.leave_school_name || leave_school_name_def;

          this.value = {...this.value,passengers_name: data.passengers_name,passengers_id: data.passengers_id,class_: data.class_,leave_school_id,leave_school_name}
        }
        if (chooseType === 'school'){
          this.setSchool({school_name: data.name,school_id: data.id});
          this.value= {school_name: data.name,school_id: data.id};
          this.getPackageType();
        }
      },
      //输入内容变化
      onChange(e){
        let {field,val} = e,
          {field_id} = field;
        if (field.field_id === 'leave_school_name'){
          this.value.leave_school_id = val.leave_school_id;
          this.value[field_id] = val.leave_school_name;
        }

        if (field_id === 'class_'){
          this.value[field_id] = val
          /*if (!/^[0-9]{3,4}$/.test(val)) {
            this.$Toast('年级班级格式不正确')
          }*/
        }
      },

      //锁票
      lockTicket(){
        return new Promise(resolve => {
          lockTicket(this.post).then(res =>{
            let {shuttle_id} = this.post
            if (res.errmsg === '已锁位不能重复提交') {
              setTimeout(() => {
                this.$router.push({path: '/ticketDetail',query: {shuttle: shuttle_id}})
              },2000);
              return
            }

            if (res.errmsg === '没有优先权'){
              let {priority_minute,sell_dateime_start,passengers_name,school_name,shuttle_id} = this.value;
              let endTime =  sell_dateime_start && new Date(crtTimeFtt(sell_dateime_start,'YYYY/MM/DD HH:mm:ss')).getTime(),
                lastTime = endTime + priority_minute *60 *1000,
                time = crtTimeFtt(lastTime,'YYYY年MM月DD日HH时mm分ss秒'),
                title = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_SYSTITLE : window.webConfig.webSystemTitle;
              this.$toast({
                duration: 2500,
                type: 'loading',
                onClose: () => {
                  this.$toast({
                    duration: 0,
                    message: `本次抢购失败，请稍后再试`,
                    className: 'm-van-loading',
                    closeOnClickOverlay: true,
                    overlay: true
                  })
                }
              })
              /* this.$toast({
                 duration: 0,
                 message: `温馨提示：感谢新客户选择${title}，请您在${time}后购票。`,
                 className: 'm-van-loading',
                 closeOnClickOverlay: true,
                 overlay: true
               })*/
              return;
            }
            if (res.errcode !== 0)return;
            let data = res.row[0];

            this.$toast({
              duration: 0,
              message:'订单已提交，排队处理中...\n请勿退出当前页面！',
              forbidClick: true,
              type: 'loading',
              className: 'm-van-loading'
            })

            this.out_trade_no = data.out_trade_no;

            //检查锁票结果
            this.checkLockResult(data.out_trade_no, data.query_cycle_second || 1 ,shuttle_id).then(() => {
              resolve();
            })
          })
        })
      },

      //检查锁票结果
      checkLockResult(id, time,shuttle_id){
        return new Promise((resolve,reject) => {
          let timer = setInterval(async () => {
            await getLockResult(id).then(res => {
              if (res.errcode !== 0){
                clearInterval(timer)
                if (res.errmsg === '没有优先权'){
                  let {priority_minute,sell_dateime_start,passengers_name,school_name,shuttle_id} = this.value;
                  let endTime =  sell_dateime_start && new Date(crtTimeFtt(sell_dateime_start,'YYYY/MM/DD HH:mm:ss')).getTime(),
                    lastTime = endTime + priority_minute *60 *1000,
                    time = crtTimeFtt(lastTime,'YYYY年MM月DD日HH时mm分ss秒'),
                    title = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_SYSTITLE : window.webConfig.webSystemTitle;

                  this.$toast({
                    duration: 2500,
                    type: 'loading',
                    onClose: () => {
                      this.$toast({
                        duration: 0,
                        message: `本次抢购失败，请稍后再试`,
                        className: 'm-van-loading',
                        closeOnClickOverlay: true,
                        overlay: true
                      })
                    }
                  })

                  /*this.$toast({
                    duration: 0,
                    message: `温馨提示：感谢新客户选择${title}，请您在${time}后购票。`,
                    className: 'm-van-loading',
                    closeOnClickOverlay: true,
                    overlay: true
                  })*/
                }
                reject();
                return;
              }
              let data = res.row[0]
              if (data && data.lock_state == 2){
                //锁票成功，发起支付
                clearInterval(timer)
                resolve();
              }
              if (data && data.lock_state == 3){
                clearInterval(timer)
                reject();
                //锁票失败
                if (data.lock_state_msg === '已锁位不能重复提交') {
                  this.$Toast(data.lock_state_msg,() =>{
                    this.$router.push({path: '/ticketDetail',query: {shuttle: shuttle_id}})
                  });
                  return
                }
                this.$Toast(data.lock_state_msg || '提交失败');
              }
            })
          },time * 1000)
        })
      },
      weUnifiedorder(id){
        return new Promise(resolve => {
          unifiedorder(id).then(res => {
            if (res.errcode !== 0)return;
            let data = res.row && res.row[0]

            /*/!*模拟测试*!/
            lockTicketTest(id).then(res=> {
              if (res.errcode !== 0) return
              this.$router.push({path: '/ticketDetail',query: {id}})
            })*/

            // 正式调起支付接口
            let onBridgeReady = ()=> {
              WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                  "appId": data.appId,     //公众号名称，由商户传入
                  "timeStamp": data.timeStamp,         //时间戳，自1970年以来的秒数
                  "nonceStr": data.nonceStr, //随机串
                  "package": data.package,
                  "signType": data.signType,         //微信签名方式：
                  "paySign": data.paySign //微信签名
                },
                (res) => {
                  if (res.err_msg == "get_brand_wcpay_request:ok") {
                    // 使用以上方式判断前端返回,微信团队郑重提示：
                    //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                    this.$Toast('支付成功',() => {
                      this.$router.push({path: '/ticketDetail',query: {id}})
                    })
                  }
                  else {
                    if (res.err_msg == "get_brand_wcpay_request:cancel") {
                      this.$Toast('取消支付',() => {
                        location.reload();
                        //取消支付后取消锁票，刷新页面--231115注释，取消解锁
                        /*
                        this.$Loading();
                        unLockTicket(id,res.err_msg).then(res => {
                          if (res.errcode !== 0) return;
                          location.reload();
                        })*/
                      })
                    }else {

                      //  支付失败
                      this.$Toast('支付失败',() => {
                        location.reload();
                        //取消支付后取消锁票，刷新页面--231115注释，取消解锁
                        /*this.$Loading();
                        unLockTicket(id,res.err_msg).then(res => {
                          if (res.errcode !== 0) return;
                          location.reload();
                        })*/
                      })
                    }
                  }
                });

            }

            if (typeof WeixinJSBridge == "undefined") {
              if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
              } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
              }
            } else {
              onBridgeReady();
            }
          })
        })
      },

      //获取套票类型
      getPackageType(def){
        this.$Loading();
        getPackage({school_id: this.schoolId}).then(res => {
          if (res.errcode !== 0)return;
          this.$toast.clear();
          //有特权码固定套票类型
          // 240130 yan 修改 有传入默认值则只显示默认套票类型
          if (def){
          // if (this.value.privileged_code && def){
            this.tabList = res.row.filter(item => item.packag_type_id === def);
            return
          }
          /*if (def){
            res.row.forEach((item,index) => {
              if (item.packag_type_id === def) this.active = index;
            })
          }*/
          // 240130 end
          this.tabList = res.row;
        })
      },
      // 获取班车套票
      getShuttlePackage_(){
        getShuttlePackage({shuttle_id: this.value.shuttle_id,packag_type_id: this.curTabId}).then(res => {
          if (res.errcode !== 0) return;
          let data = res.row;
          this.packageList = data || [];

          let {query} = this.$route,
            {ticket_typall_id } = query;
          if (ticket_typall_id){
            this.ticket_typall_id = ticket_typall_id;
            return
          }
          if (data[0]){
            this.ticket_typall_id = data[0].ticket_typall_id
          }
        });
      },

      //优先购票判断
      isPriorityTicket(){
        return new Promise(resolve => {
          let {priority_minute,sell_dateime_start,passengers_name,school_name,shuttle_id} = this.value;
          priority_minute = Number(priority_minute);
          if (!priority_minute) {
            resolve();
            return;
          }
          let nowTime = new Date().getTime(),
            endTime =  sell_dateime_start && new Date(crtTimeFtt(sell_dateime_start,'YYYY/MM/DD HH:mm:ss')).getTime(),
            lastTime = endTime + priority_minute *60 *1000;
          //取消时间限制判断
          /*if (nowTime > lastTime) {
            resolve();
            return
          }*/
          checkPriorityPassengers({school_name,passengers_name,shuttle_id}).then(res => {
            if (res.errcode != 0) {
              let msg = res.errmsg;
              if (res.errmsg === '没有优先权'){
                let time = crtTimeFtt(lastTime,'YYYY年MM月DD日HH时mm分ss秒'),
                  title = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_SYSTITLE : window.webConfig.webSystemTitle;
                msg = `温馨提示：感谢新客户选择${title}，请您在${time}后购票。`
                this.$toast({
                  duration: 2500,
                  type: 'loading',
                  onClose: () => {
                    this.$toast({
                      duration: 0,
                      message: `本次抢购失败，请稍后再试`,
                      className: 'm-van-loading',
                      closeOnClickOverlay: true,
                      overlay: true
                    })
                  }
                })
              }else {
                this.$toast({
                  duration: 0,
                  message: msg,
                  className: 'm-van-loading',
                  closeOnClickOverlay: true,
                  overlay: true
                })
              }
              /*this.$toast({
                duration: 0,
                message: msg,
                className: 'm-van-loading',
                closeOnClickOverlay: true,
                overlay: true
              })*/
            }else{
              resolve();
            }
          })
        })
      },

      /*// 清空画布
      handleReset () {
        this.$refs.esign.reset()
      },
      // 生成签名的base64图片
      handleGenerate () {
        this.$refs.esign.generate().then(async res => {//res：base64图片地址
          // this.imgSrc = res;
          let local = '佛山市·梁园',
            now = new Date(),
            date = crtTimeFtt(now,'YYYY-MM-DD HH:mm');
          // await this.getLocation().then(name => local = name);
          let opts = [
            {
              content: local,
              font: '20px serif',
              position: {
                bottom: 10,
                left: 10
              }
            },
            {
              content: date,
              font: '26px serif',
              position: {
                bottom: 40,
                left: 10
              }
            },
          ]
          this.addWatermark(res,opts).then(res=>{
            console.log(res);
            this.signImg = res;
            this.showSignPopup = false;

            this.$Loading();
          //  上传协议和签名
            this.submitOrderImg().then(() => {
              this.$toast.clear();
              console.log('发起支付');
              //发起支付
              let {out_trade_no} = this;
              this.weUnifiedorder(out_trade_no).then(() => {})
            });
          })
          // console.log(res,base64ImgtoFile(res))
        }).catch(err => {
          console.log('画布没有签字时会执行这里 Not Signned')
          this.$Toast('请签名确认购票。')
        })
      },
      //显示签名
      bindShowESign(){
        let {clientHeight,clientWidth} = this.$refs.esignWrap;
        this.esignH = clientHeight;
        this.esignW = clientWidth;
        this.showSign = true;
      },
      //取消签名-取消购票，发起解锁
      cancelSign(){
        this.showSignPopup = false;
        this.handleReset();
      },
      getLocation(){
        return new Promise(resolve => {
          this.$Loading();
          getLocation().then(res => {
            let {latitude,longitude} = res;
            if (!latitude || !longitude)return;
            mapGeocoder({
              "key": process.env.NODE_ENV === 'development' ? process.env.VUE_APP_MAPKEY : window.webConfig.webMapKey,
              "location": `${latitude},${longitude}`,
              "get_poi": "",
              "poi_options": "",
              "output": "",
              "callback": ""
            }).then(res =>{
              let {result} = res,
                {city,district} = result.address_component,
                {recommend} = result.formatted_addresses;
              console.log(city);
              console.log(recommend);
              resolve(`${city}·${recommend}`);
              this.$toast.clear();
            })
          },err => {
            this.$toast.clear();
            dialog.alert('无法获取您的定位','为记录您的购票位置信息，需要请您到设置中开启定位权限','知道了')
            // resolve('');
          })
        })
      },
      /!**
       * 签名添加水印
       * @param src 签名图片地址base64
       * @param opts 水印参数
       * @return {Promise<any>} 返回已添加水印的签名图片地址base64
       *!/
      addWatermark(src,opts) {
        return new Promise((resolve,reject) => {
          const img = new Image();
          img.src = src;
          img.setAttribute('crossOrigin', 'Anonymous')
          img.onload = () => {
            let canvas = document.createElement('canvas')
            let context = canvas.getContext('2d')
            /!*if (rotate > 45 && rotate <= 135) { // 90 宽高颠倒
              canvas.width = img.height
              canvas.height = img.width
            } else if (rotate > 225 && rotate <= 315) { // 270 宽高颠倒
              canvas.width = img.height
              canvas.height = img.width
            } else {
              canvas.width = img.width
              canvas.height = img.height
            }*!/
            let rotate = 270;  //旋转270度
            const {width: originWidth, height: originHeight} = img;
            canvas.width = originHeight;
            canvas.height = originWidth;
            context.clearRect(0, 0, canvas.width, canvas.height)
            context.translate(canvas.width / 2, canvas.height / 2)
            context.rotate(rotate * Math.PI / 180)
            context.translate(-canvas.width / 2, -canvas.height / 2)
            context.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2, img.width, img.height)
            context.translate(canvas.width / 2, canvas.height / 2)
            context.rotate(-rotate * Math.PI / 180)
            context.translate(-canvas.width / 2, -canvas.height / 2)
            context.restore();

            this.imgSrc = canvas.toDataURL();

            //添加水印
            fillText(context, opts, originHeight, originWidth);

            let base64 = canvas.toDataURL();
            resolve(base64);

          }
          img.onerror = reject

        })
      },*/

      //提交签名图片，协议图片
      submitOrderImg(){
        return new Promise(resolve => {
          let {imgSrc,signImg,agreementImg,out_trade_no} = this,
            signFile = new FormData(),
            agreementFile = new FormData();

          signFile.append('file',base64ImgtoFile(signImg));
          agreementFile.append('file',base64ImgtoFile(agreementImg));

          Promise.all([uploadFile(signFile),uploadFile(agreementFile)]).then(res =>{
            let agreement_handwritten_pic,agreement_all_pic;

            res.forEach((item,i) =>{
              if (item.errcode != 0) return
              let data = item.row[0];
              if (i) agreement_all_pic = data.url;
              else agreement_handwritten_pic = data.url;
            });
            if (!agreement_all_pic || !agreement_handwritten_pic) return
            updateOrderImg({
              out_trade_no,
              agreement_handwritten_pic,
              agreement_all_pic
            }).then(res => {
              if (res.errcode != 0) return;
              resolve()
            })
          })
        })
      },

      //检查监护人信息
      checkCustomerData(){
        return new Promise(resolve => {
          let {customerName,customerPhone} = this;
          if (!customerName || !customerPhone){
            dialog.alert('提示','为保证购票成功，请先完善监护人信息','去填写').then(() =>{
              this.$router.push({ path: '/guardian' })
            },()=>{});
          }else resolve();
        })
      },

    //  检查是否需要阅读协议签名
      checkSignature(){
        return new Promise(resolve => {
          let {shuttle_id,packag_type_id,ticket_typall_id,passengers_id} = this.post;
          let post = {shuttle_id,packag_type_id,ticket_typall_id,passengers_id},
            result = true;
          checkAgreement(post).then(res =>{
            if (res.errcode !== 0 ) {
              resolve(result);
              return;
            }
            let data = res.row[0];
            if (!data) return;
            result = data.TF;
            resolve(result);
          })
        })
      },

    },
    async mounted(){
      this.$Loading();
      let {query} = this.$route,
        {token,privileged_code,school_id,school_name,packag_type_id,shuttle_id,stop_id_go,stop_name_go,stop_id_leave,stop_name_leave,ticket_typall_id } = query;

      if (token){
        setToken(token);
        await this.$store.dispatch('getCustomer')

        let query = this.$route.query;
        delete query.token;
        let keys = Object.keys(query),
          param = keys.map(item => item = item + '=' + query[item]),
          dir = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_SECONDDIR : window.webConfig.webSecondDir
        // location.replace(`/dist/buyTicket?${param.join('&')} `);
        location.replace(`${dir}buyTicket?${param.join('&')} `);
        return
      }
      this.checkCustomerData();
      getLeaveSchoolType().then(res => {
        if (res.errcode !== 0)return;
        this.fields.backHomeField.options = res.row;
        this.fields.backHomeField.value = 'js001';
        this.$toast.clear();
      })
      //传入学校id 和 套票类型id
      if (school_id && packag_type_id ) {
        this.setSchool({school_name,school_id});
        this.value = {...this.value,...query}
        this.value.privileged_code = privileged_code;
        this.getPackageType(packag_type_id);
        shuttle_id && getShuttle(query).then(res => {
          if (res.errcode !== 0) return;
          this.$toast.clear();
          let row = res.row[0];
          this.value = {...this.value,...row,}
          this.getShuttlePackage_();
        })
        return
      }

      this.onShow('school');

      //获取已选学校直接填充
      if (this.schoolId) {
        this.value = {...this.value,school_name: this.schoolName, school_id: this.schoolId};
        this.getPackageType();
      }else {
        // this.onShow('school');
      }

    },

  }
</script>

<style scoped lang="less">
    .main{
        padding: 0 10px;
        overflow: auto;
        .box{
            background: #fff;
            border-radius: 2px;
            margin-bottom: 10px;
            padding: 0 15px ;
        }
        .school-wrap{
            display: flex;
            align-items: center;
            height: 50px;
            font-size: 14px;
            color: #333;
            .bold{
                font-weight: bold;
                font-size: 17px;
            }
            .btn{
                color: #24C373;
                height: 100%;
                line-height: 50px;
                padding: 0 10px;

            }
        }
        .tab-wrap{
            display: flex;
            position: relative;
            & > li{
                width: 100%;
                display: flex;
                justify-content: center;
                font-size: 16px;
                height: 50px;
                align-items: center;
                &.active{
                    position: relative;
                    color: #24C373;
                    /*&:after{
                        content: '';
                        position: absolute;
                        display: block;
                        width: 20px;
                        height: 2px;
                        background: #24C373;
                        bottom: 0;
                        left: 50%;
                        transform: translateX(-50%);
                    }*/
                }
            }
            .line{
                position: absolute;
                bottom: 0;
                display: block;
                width: 20px;
                height: 2px;
                background: #24C373;
                /*transform: translateX(55px) translateX(-50%);*/
                transition: all 0.1s linear;
            }
        }
        .cell{
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: center;
            font-size: 15px;
            min-height: 44px;
            & + .cell{
                border-top: 1px solid #dedede;
            }
            .cell-right{
                text-align: right;
                flex: 1;
                .cell-value{
                    text-align: right;
                }
            }

            .tips{
                color: #999999;
                font-size: 13px;
                padding-bottom: 10px;
            }
        }
        .gdot,.rdot{
            &:before{
                content: '';
                display: inline-block;
                width: 9px;
                height: 9px;
                border-radius: 9px;
                background: #24C373;
                margin-right: 5px;
            }
        }
        .rdot:before{
            background: #FF5B13;
        }

        .schedule-wrap{
            .title{
                padding: 10px 0;
            }
            .h1{
                color: #333;
                font-size: 15px;
                line-height: 21px;
            }
            .h2{
                color: #333;
                font-size: 14px;
                line-height: 21px;
            }
            .h3{
                color: #24C373;
                font-size: 13px;
            }
            .bold{
                font-weight: bold;
            }
            .margin-bot10{
                margin-bottom: 10px;
            }
            .ticket-type{
                border-top: 1px solid #dedede;
            }
        }
    }
    .footer{
        padding: 10px;
        .btn{
            width: 100%;
        }
    }
    .esign-wrap{
        width: 100vw;
        height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        flex-direction: column;
        .esign{
            flex: 1;
            height: 0;
            width: 100%;
        }
        .btns{
            display: flex;
            align-self: center;
            flex-shrink: 0;
            width: 100%;
            height: 100px;
            .btn-wrap{
                transform: rotate(90deg);
                width: 90px;
                height: 90px;
                .btn{
                    width: 90px;
                }
            }
        }

    }
    /deep/.van-radio__icon{
        padding-top: 3px;
      align-self: flex-start;
    }
</style>
